<template>
  <div>
    <div class="flex flex-col gap-4">
      <!-- File Upload Section -->
      <div class="form-control">
        <label class="label">
          <span class="label-text text-sm font-semibold">Excel文件</span>
        </label>
        <div class="flex gap-2">
          <input type="file" 
                 ref="fileInput" 
                 accept=".xlsx,.xls" 
                 @change="handleFileChange" 
                 class="hidden"/>
          <button class="btn btn-neutral btn-outline btn-sm"
                  @click="triggerFileUpload">
            选择文件
          </button>
          <span v-if="fileName" class="text-sm self-center">{{ fileName }}</span>
        </div>
        <div class="text-sm text-gray-500 mt-1">
          请上传Excel文件，文件格式要求：账号、密码、姓名、手机号、角色、学校、年级、班级、学号/工号
        </div>
      </div>

      <!-- Import Summary -->
      <div v-if="importSummary" class="alert alert-info">
        <div class="font-semibold">导入结果：</div>
        <div>成功：{{ importSummary.success.length }} 条</div>
        <div>失败：{{ importSummary.fail.length }} 条</div>
        <div v-if="importSummary.fail.length > 0" class="mt-2">
          <div class="font-semibold">失败详情：</div>
          <ul class="list-disc list-inside text-sm text-red-600">
            <li v-for="(item, idx) in importSummary.fail" :key="idx">{{ item }}</li>
          </ul>
        </div>
        <div v-if="importSummary.success.length > 0" class="mt-2">
          <div class="font-semibold">成功账号：</div>
          <ul class="list-disc list-inside text-sm text-green-600">
            <li v-for="(item, idx) in importSummary.success" :key="idx">{{ item }}</li>
          </ul>
        </div>
      </div>

      <!-- AG Grid Section -->
      <div v-if="gridData.length > 0" :style="`height: ${Math.min(52 * gridData.length + 52, 600)}px`" class="w-full">
        <ag-grid-vue
          class="ag-theme-alpine w-full h-full"
          :columnDefs="columnDefs"
          :rowData="gridData"
          :defaultColDef="defaultColDef"
          :enableCellTextSelection="true"
          :ensureDomOrder="true"
          :getRowClass="getRowClass"
          :getRowStyle="getRowStyle"
          :tooltipShowDelay="0"
          :tooltipHideDelay="2000"
          @grid-ready="onGridReady"
        >
        </ag-grid-vue>
      </div>

      <!-- Action Buttons -->
      <div v-if="gridData.length > 0" class="flex gap-2 justify-end">
        <button class="btn btn-error btn-sm" @click="cancelImport">取消</button>
        <button class="btn btn-success btn-sm" 
                @click="confirmImport" 
                :disabled="isImporting">
          确认导入
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { AgGridVue } from 'ag-grid-vue3'
import { ModuleRegistry, AllCommunityModule } from 'ag-grid-community'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import * as XLSX from 'xlsx'
import { httpPost } from '~/utils/http/http-helper.js'
import { notificationError, notificationSuccess, notificationWarning } from '~/utils/notification/index.js'
import auth from '~/utils/auth/index.js'

// Register AG Grid modules
ModuleRegistry.registerModules([AllCommunityModule])

const emit = defineEmits(['import-complete', 'import-cancel'])

const fileInput = ref(null)
const fileName = ref('')
const gridData = ref([])
const gridApi = ref(null)
const importSummary = ref(null)
const isImporting = ref(false)
const failedRows = ref(new Set())
const rowErrors = ref(new Map())
const loginUser = ref(null)
const loginUserRef = computed(() => {
  if (!loginUser.value) {
    loginUser.value = auth.getLocalUser()
  }
  return loginUser.value || {}
})

// Function to check if user is a teacher
const isTeacher = computed(() => loginUserRef.value?.role === '教师')
const teacherSchool = computed(() => loginUserRef.value?.xuexiao)

// Function to validate school value for teachers
function validateSchoolValue(value, rowData) {
  if (isTeacher.value) {
    // For teachers, empty value is allowed (will be filled with teacher's school)
    if (!value) return true
    // Non-empty value must match teacher's school
    return value === teacherSchool.value
  }
  return true
}

// Function to get school value for display/editing
function getSchoolValue(params) {
  // For teachers, show their school if value is empty
  if (isTeacher.value && !params.value) {
    return teacherSchool.value
  }
  // For all users, return the actual value
  return params.value || ''
}

// Function to set school value
function setSchoolValue(params) {
  if (isTeacher.value) {
    // For teachers, only allow empty value or their own school
    if (!params.newValue || params.newValue === teacherSchool.value) {
      params.value = params.newValue || teacherSchool.value
      return true
    }
    return false
  }
  // For non-teachers, allow any value
  params.value = params.newValue
  return true
}

// Function to validate role value for teachers
function validateRoleValue(value, rowData) {
  if (isTeacher.value) {
    // For teachers, empty value is allowed (will be filled with '学生')
    if (!value) return true
    // Non-empty value must be '学生'
    return value === '学生'
  }
  return true
}

// Function to get role value for display/editing
function getRoleValue(params) {
  // For teachers, show '学生' if value is empty
  if (isTeacher.value && !params.value) {
    return '学生'
  }
  // For all users, return the actual value
  return params.value || ''
}

// Function to set role value
function setRoleValue(params) {
  if (isTeacher.value) {
    // For teachers, only allow empty value or '学生'
    if (!params.newValue || params.newValue === '学生') {
      params.value = params.newValue || '学生'
      return true
    }
    return false
  }
  // For non-teachers, allow any valid role
  if (!params.newValue || ['超级管理员', '教师', '学生'].includes(params.newValue)) {
    params.value = params.newValue
    return true
  }
  return false
}

// Move columnDefs to be a computed property
const columnDefs = computed(() => [
  { 
    field: 'account', 
    headerName: '账号',
    minWidth: 150
  },
  { 
    field: 'password', 
    headerName: '密码',
    minWidth: 150
  },
  { 
    field: 'name', 
    headerName: '姓名',
    minWidth: 120
  },
  { 
    field: 'cellphoneNumber', 
    headerName: '手机号',
    minWidth: 150
  },
  { 
    field: 'role', 
    headerName: '角色',
    minWidth: 120,
    editable: !isTeacher.value,
    valueGetter: params => {
      // For admin, just return the value
      if (!isTeacher.value) {
        return params.data?.role || ''
      }
      // For teacher, return '学生' if empty
      return params.data?.role || '学生'
    },
    valueSetter: params => {
      const newValue = params.newValue?.trim() || ''
      // For admin, allow any valid role
      if (!isTeacher.value) {
        if (!newValue || ['超级管理员', '教师', '学生'].includes(newValue)) {
          params.data.role = newValue
          return true
        }
        return false
      }
      // For teacher, only allow '学生'
      if (!newValue || newValue === '学生') {
        params.data.role = newValue || '学生'
        return true
      }
      return false
    },
    cellEditor: 'agSelectCellEditor',
    cellEditorParams: {
      values: isTeacher.value ? ['学生'] : ['超级管理员', '教师', '学生']
    },
    cellStyle: params => {
      if (isTeacher.value) {
        return { backgroundColor: '#f3f4f6' }
      }
      return null
    }
  },
  { 
    field: 'xuexiao', 
    headerName: '学校',
    minWidth: 150,
    editable: !isTeacher.value,
    valueGetter: params => {
      // For admin, just return the value
      if (!isTeacher.value) {
        return params.data?.xuexiao || ''
      }
      // For teacher, return their school if empty
      return params.data?.xuexiao || teacherSchool.value
    },
    valueSetter: params => {
      const newValue = params.newValue?.trim() || ''
      // For admin, allow any value
      if (!isTeacher.value) {
        params.data.xuexiao = newValue
        return true
      }
      // For teacher, only allow their school
      if (!newValue || newValue === teacherSchool.value) {
        params.data.xuexiao = newValue || teacherSchool.value
        return true
      }
      return false
    },
    cellStyle: params => {
      if (isTeacher.value) {
        return { backgroundColor: '#f3f4f6' }
      }
      return null
    }
  },
  { 
    field: 'nianji', 
    headerName: '年级',
    minWidth: 120
  },
  { 
    field: 'banji', 
    headerName: '班级',
    minWidth: 120
  },
  { 
    field: 'xuehao', 
    headerName: '学号/工号',
    minWidth: 150,
    valueFormatter: params => {
      return params.value ? String(params.value) : ''
    }
  }
])

const defaultColDef = {
  flex: 1,
  minWidth: 120,
  resizable: true,
  sortable: true,
  filter: true,
  editable: true,
  tooltipValueGetter: params => {
    if (failedRows.value.has(params.node.rowIndex)) {
      return rowErrors.value.get(params.node.rowIndex)
    }
    return null
  }
}

function triggerFileUpload() {
  fileInput.value.click()
}

function handleFileChange(event) {
  const file = event.target.files[0]
  if (!file) return

  fileName.value = file.name
  const reader = new FileReader()
  
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
      const jsonData = XLSX.utils.sheet_to_json(firstSheet)

      // Transform the data to match our expected format
      let transformedData = jsonData.map(row => {
        const role = String(row['角色'] || '').trim()
        const xuexiao = String(row['学校'] || '').trim()
        
        return {
          account: String(row['账号'] || ''),
          password: String(row['密码'] || ''),
          name: String(row['姓名'] || ''),
          cellphoneNumber: String(row['手机号'] || ''),
          role: role,
          xuexiao: xuexiao,
          nianji: String(row['年级'] || ''),
          banji: String(row['班级'] || ''),
          xuehao: row['学号/工号'] ? String(row['学号/工号']) : ''
        }
      })

      // For teachers, filter data immediately
      if (isTeacher.value) {
        const originalCount = transformedData.length
        // Filter out non-qualified data
        transformedData = transformedData.filter(row => {
          const schoolMatch = !row.xuexiao || row.xuexiao === teacherSchool.value
          const roleMatch = !row.role || row.role === '学生'
          return schoolMatch && roleMatch
        })
        
        // Set default values for remaining data
        transformedData = transformedData.map(row => ({
          ...row,
          role: row.role || '学生',
          xuexiao: row.xuexiao || teacherSchool.value
        }))
        
        // Show warning if any data was filtered out
        if (transformedData.length < originalCount) {
          const filteredCount = originalCount - transformedData.length
          notificationWarning(`已过滤 ${filteredCount} 条不符合要求的数据（非本校或非学生角色）`)
        }
      }

      // Update grid data with filtered/transformed data
      gridData.value = transformedData

      // Force grid refresh to update the view
      nextTick(() => {
        if (gridApi.value) {
          gridApi.value.refreshCells()
          gridApi.value.sizeColumnsToFit()
        }
      })

    } catch (error) {
      console.error('File processing error:', error)
      notificationError('文件解析失败：' + error.message)
      resetImport()
    }
  }

  reader.readAsArrayBuffer(file)
}

function onGridReady(params) {
  gridApi.value = params.api
  
  // Initial column sizing
  params.api.sizeColumnsToFit()
  
  // Watch for changes in loginUserRef to refresh the grid
  watch([loginUserRef, isTeacher], () => {
    if (gridApi.value) {
      console.log('Grid refresh triggered - User Role:', loginUserRef.value?.role)
      gridApi.value.refreshCells()
      gridApi.value.sizeColumnsToFit()
    }
  }, { deep: true, immediate: true })
}

function cancelImport() {
  resetImport()
  emit('import-cancel')
}

function getRowClass(params) {
  if (failedRows.value.has(params.node.rowIndex)) {
    return 'ag-row-error'
  }
  return ''
}

function getRowStyle(params) {
  if (failedRows.value.has(params.node.rowIndex)) {
    return {
      'border-left': '4px solid #ef4444',
      'background-color': '#fee2e2',
      'font-weight': '500'
    }
  }
  return {}
}

function scrollToErrorRow(error) {
  const match = error.match(/第(\d+)行/)
  if (match) {
    const rowIndex = parseInt(match[1]) - 1
    const rowNode = gridApi.value.getRowNode(rowIndex)
    if (rowNode) {
      rowNode.setSelected(true)
      gridApi.value.ensureIndexVisible(rowIndex, 'middle')
    }
  }
}

async function confirmImport() {
  try {
    isImporting.value = true
    failedRows.value.clear()
    rowErrors.value.clear()
    importSummary.value = null

    // Get the final data from the grid
    const finalData = []
    gridApi.value.forEachNode(node => {
      if (node.data) {
        // For teachers, ensure role is set to '学生' if empty
        if (isTeacher.value && !node.data.role) {
          node.data.role = '学生'
        }
        // For teachers, ensure school is set to their school if empty
        if (isTeacher.value && !node.data.xuexiao) {
          node.data.xuexiao = teacherSchool.value
        }
        finalData.push(node.data)
      }
    })

    // Validate data
    const validationErrors = validateData(finalData)
    if (validationErrors.length > 0) {
      notificationError('数据验证失败：\n' + validationErrors.join('\n'))
      return
    }

    // Send to backend
    const response = await httpPost('/api/user/bulk-import', finalData)
    if (response.success) {
      importSummary.value = {
        success: response.data.success || [],
        fail: response.data.fail || []
      }

      // Mark failed rows and store error messages
      if (response.data.fail && response.data.fail.length > 0) {
        response.data.fail.forEach(error => {
          const match = error.match(/第(\d+)行/)
          if (match) {
            const rowIndex = parseInt(match[1]) - 1
            failedRows.value.add(rowIndex)
            rowErrors.value.set(rowIndex, error)
          }
        })
      }

      // Refresh the grid to show the error styling
      gridApi.value.refreshCells()

      if (response.data.success && response.data.success.length > 0) {
        notificationSuccess(`成功导入 ${response.data.success.length} 条数据`)
      }
      if (response.data.fail && response.data.fail.length > 0) {
        notificationError(`导入失败 ${response.data.fail.length} 条数据，请查看详情`)
      }

      // Only emit complete if all rows were successful
      if (response.data.fail && response.data.fail.length === 0) {
        resetImport()
        emit('import-complete')
      }
    } else {
      notificationError(response.msg || '导入失败')
    }
  } catch (error) {
    notificationError('导入失败：' + error.message)
  } finally {
    isImporting.value = false
  }
}

function validateData(data) {
  const errors = []
  data.forEach((row, index) => {
    if (!row.account) errors.push(`第${index + 1}行：账号不能为空`)
    if (!row.password) errors.push(`第${index + 1}行：密码不能为空`)
    if (!row.name) errors.push(`第${index + 1}行：姓名不能为空`)
    if (!row.cellphoneNumber) errors.push(`第${index + 1}行：手机号不能为空`)
    
    // Role validation based on user type
    if (isTeacher.value) {
      if (row.role && row.role !== '学生') {
        errors.push(`第${index + 1}行：教师只能导入学生账号`)
      }
    } else {
      if (!row.role) {
        errors.push(`第${index + 1}行：角色不能为空`)
      } else if (!['超级管理员', '教师', '学生'].includes(row.role)) {
        errors.push(`第${index + 1}行：角色必须是"超级管理员"、"教师"或"学生"`)
      }
    }

    // School validation
    if (isTeacher.value) {
      if (row.xuexiao && row.xuexiao !== teacherSchool.value) {
        errors.push(`第${index + 1}行：学校必须是"${teacherSchool.value}"`)
      }
    } else if (!row.xuexiao) {
      errors.push(`第${index + 1}行：学校不能为空`)
    }

    if (!row.xuehao) errors.push(`第${index + 1}行：学号/工号不能为空`)
  })
  return errors
}

function resetImport() {
  fileName.value = ''
  gridData.value = []
  importSummary.value = null
  failedRows.value.clear()
  rowErrors.value.clear()
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}
</script>

<style scoped>
.ag-theme-alpine {
  --ag-header-height: 40px;
  --ag-header-foreground-color: #1f2937;
  --ag-header-background-color: #f3f4f6;
  --ag-odd-row-background-color: #f9fafb;
  --ag-header-cell-hover-background-color: #e5e7eb;
  --ag-row-hover-color: #e5e7eb;
}

:deep(.ag-row-error) {
  background-color: #fee2e2 !important;
}

:deep(.ag-row-error:hover) {
  background-color: #fecaca !important;
}

:deep(.ag-tooltip) {
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
  max-width: 300px;
  white-space: normal;
  word-wrap: break-word;
}

:deep(.ag-row-selected) {
  background-color: #fecaca !important;
}

:deep(.ag-row-selected:hover) {
  background-color: #fca5a5 !important;
}

:deep(.ag-cell[col-id="xuexiao"]),
:deep(.ag-cell[col-id="role"]) {
  background-color: #f3f4f6;
}
</style> 